package com.lin.eventbus

import com.lin.eventbus.exception.InternalEventChannelNotFoundException
import com.lin.eventbus.exception.InternalEventListenerNotFoundException
import com.lin.eventbus.internal.InternalInternalEventBus
import org.junit.Assert.*
import org.junit.Test


class EventBusTest {

    class EventBusTestEvent : Event()

    @Test
    fun channelNotFound() {
        val channel = "/${com.lin.eventbus.util.RandomUtils.nextObjectId()}"
        val future = EventBus.publish(channel, EventBusTestEvent())
        try {
            future.get()
            fail()
        } catch (ex: com.lin.eventbus.exception.EventBusException) {
            assertTrue(ex.cause is
                    InternalEventChannelNotFoundException
            )
        }
    }

    @Test
    fun listenerNotFound() {
        val channel = "/${com.lin.eventbus.util.RandomUtils.nextObjectId()}"
        com.lin.eventbus.EventBus.register(channel, 32, 1)

        try {
            val future = EventBus.publish(channel, EventBusTestEvent())
            try {
                future.get()
                fail()
            } catch (ex: com.lin.eventbus.exception.EventBusException) {
                assertTrue(ex.cause is InternalEventListenerNotFoundException)
            }
        } finally {
            com.lin.eventbus.EventBus.unregister(channel)
        }
    }

    @Test
    fun execute() {
        InternalInternalEventBus.INSTANCE.initialize()

        val s = com.lin.eventbus.util.RandomUtils.nextObjectId()
        assertEquals(s, echo(s))
        val i = com.lin.eventbus.util.RandomUtils.nextObjectId()
        assertEquals(i, echo(i))
        assertNull(echo(null))
    }

    private fun echo(input: Any?): Any? {
        return com.lin.eventbus.EventBus.execute { input }.get()
    }
}